{% load i18n %}
<div class="row">
  <div class="col-2">
    <form role="form" method="post" action="{{request.prefix}}/execute/launch/exporttofolder/">{% csrf_token %}
      <button type="submit" class="btn btn-primary" id="exporttofolder" value="{% trans "export"|capfirst %}">{% trans "export"|capfirst %}</button>
    </form>
  </div>
  <div class="col-10">
    <p>{% trans "Exports the plan (purchase orders, distribution orders and manufacturing orders) as a set of CSV files." %}</p>
  </div>
</div>
<div class="row mb-2">
  <div class="col flex-grow-1 offset-2"><strong>{% trans 'file name'|capfirst %}</strong></div>
  <div class="col-1 text-center"><strong>{% trans 'size'|capfirst %}</strong></div>
  <div class="col-2 text-center"><strong>{% trans 'changed'|capfirst %}</strong></div>
  <div class="col-auto text-center">
    <div class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-placement="top"
      data-bs-title="{% trans 'Download all files' %}" onClick="downloadExportFile(1)">
      <span class="fa fa-arrow-down"></span>
    </div>
    <div class="btn btn-sm btn-danger deletefile" data-bs-toggle="tooltip" data-bs-placement="top"
      data-bs-title="{% trans 'Delete all files' %}" onClick="deleteExportFile(1)">
      <span class="fa fa-close"></span>
    </div>
    <div class="btn btn-sm invisible btn-primary">
      <span class="fa fa-edit"></span>
    </div>
  </div>
</div>
{% for j in data_exports %}
<div class="row mb-2" data-file="{{j.name}}">
  <div class="col flex-grow-1 offset-2">{{j.name}}</div>
  <div class="col-auto text-nowrap text-center">{{j.size}}</div>
  <div class="col-auto text-nowrap text-center">{{j.timestamp}}</div>
  <div class="col-auto text-center">
    <button class="btn btn-sm btn-primary downloadfile" data-bs-toggle="tooltip"{% if not j.timestamp %} disabled{% endif %}
      data-bs-placement="top" data-bs-title="Download file" onClick="downloadExportFile(1, '{{j.name}}')">
      <span class="fa fa-arrow-down"></span>
    </button>
    <button class="btn btn-sm btn-danger deletefile" data-bs-toggle="tooltip"{% if not j.timestamp %} disabled{% endif %}
      data-bs-placement="top" data-bs-title="{% trans "Delete file" %}" onClick="deleteExportFile(1, '{{j.name}}')">
      <span class="fa fa-close"></span>
    </button>
    <div class="btn btn-sm btn-primary" onclick="toggleAddExport(true, this)"
      data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Edit" %}">
      <span class="fa fa-edit" ></span>
    </div>
  </div>
</div>
<div class="row mb-3 d-none" data-file="{{j.name}}"
  style="border-style:solid; border-radius:10px; border-width:1px; margin:10px 0 10px 0">
    <div class="col-auto">
      <button class="btn btn-primary w-100" onclick="saveExport(this)" style="margin-top: 15px">
        {% trans "Save" %}
      </button>
      <button class="btn btn-primary w-100" onclick="deleteExport(this)" style="margin-top: 15px">
        {% trans "delete" %}
      </button>
    </div>
    <div class="col">
        <div class="row mb-3 mt-3">
          <div class="col-3">{% trans "name"|capfirst %}
          </div>
          <div class="col-9">
            <div class="input-group">
                <input type="text" class="form-control add-export-name" data-field="name" value="{{j.basename}}" placeholder="Unique name">
                <button class="btn btn-outline-primary dropdown-toggle add-export-extension" type="button" data-bs-toggle="dropdown" aria-expanded="false">{{j.extension}}</button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.csv')">.csv</a></li>
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.csv.gz')">.csv.gz</a></li>
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.xlsx')">.xlsx</a></li>
                </ul>
            </div>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-3">{% trans "type"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select add-export-type" aria-label="Select export type" onchange="changeExportType(this)">
               <option disabled value>{% trans "Select export type" %}</option>
               <option{% if j.exporttype == "sql" %} selected{% endif %} value="sql">SQL query</option>
               <option{% if j.exporttype == "report" %} selected{% endif %} value="report">Report</option>
               <option{% if j.exporttype == "customreport" %} selected{% endif %} value="customreport">Custom report</option>
             </select>
          </div>
        </div>
        <div class="{% if j.exporttype != "sql" %}d-none {% endif %}row mb-3 optional" data-type="sql">
          <div class="col">
             <div class="form-floating">
               <textarea class="form-control add-export-sql">{{j.sql | default:''}}</textarea>
               <label>SQL query</label>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "customreport" %}d-none {% endif %}row mb-3 optional" data-type="customreport">
          <div class="col-3 text-nowrap">{% trans "custom report"|capfirst%}</div>
          <div class="col-9">
             <select class="form-select add-export-customreport" aria-label="Select custom report">
               <option disabled value>{% trans "Select report" %}</option>
               {% for r in customreports %}<option {% if j.reportid == r.1 %}selected {% endif %}value="{{r.1}}">{{r.0}}</option>{% endfor %}
             </select>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "report"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select add-export-report">
               <option disabled selected value>{% trans "Select report" %}</option>
               {% for r in reports %}<option {% if j.report == r.1 %}selected {% endif %}value="{{r.1}}">{{r.0}}</option>{% endfor %}
             </select>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "bucket size"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select w-auto add-export-bucket">
               <option{% if j.arguments.buckets == "day" %} selected{% endif %} value="day">day</option>
               <option{% if j.arguments.buckets == "week" %} selected{% endif %}  value="week">week</option>
               <option{% if j.arguments.buckets == "month" %} selected{% endif %}  value="month">month</option>
               <option{% if j.arguments.buckets == "quarter" %} selected{% endif %}  value="quarter">quarter</option>
               <option{% if j.arguments.buckets == "year" %} selected{% endif %}  value="year">year</option>
             </select>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "horizon"|capfirst %}</div>
          <div class="col-9">
             <input style="width:4.5em" type="number" class="form-control d-inline arrows add-export-horizon" min="0" max="99" value="{{j.arguments.horizonlength}}">
             <select class="form-select d-inline w-auto add-export-horizonbucket">
               <option{% if j.arguments.horizonunit == "day" %} selected{% endif %} value="day">day</option>
               <option{% if j.arguments.horizonunit == "week" %} selected{% endif %} value="week" selected>week</option>
               <option{% if j.arguments.horizonunit == "month" %} selected{% endif %} value="month">month</option>
               <option{% if j.arguments.horizonunit == "quarter" %} selected{% endif %} value="quarter">quarter</option>
               <option{% if j.arguments.horizonunit == "year" %} selected{% endif %} value="year">year</option>
             </select>
          </div>
        </div>
  </div>
  <div class="col-auto mt-3 mb-3">
    <button type="button" class="btn-close float-end" onclick="toggleAddExport(false, this)"></button>
  </div>
</div>
{% endfor %}

<!-- row for the plus icon to add an export -->
<div class="row" data-file="adding-a-new-export">
  <div class="col-auto text-center ms-auto">
      <div class="btn btn-sm btn-primary" id="export_add" onclick="toggleAddExport(true, this)" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Add" %}">
      <span class="fa fa-plus"></span>
      </div>
  </div>
</div>

<!-- Add an export -->
<div class="row d-none" data-file="adding-a-new-export"
  style="border-style:solid; border-radius:10px; border-width:1px; margin:10px 0 10px 0">
    <div class="col-auto">
      <button class="btn btn-primary w-100" onclick="saveExport(this)" style="margin-top: 15px">
        {% trans "Save" %}
      </button>
    </div>
    <div class="col">
        <div class="row mb-3 mt-3">
          <div class="col-3">{% trans "name"|capfirst %}
          </div>
          <div class="col-9">
            <div class="input-group">
                <input type="text" class="form-control add-export-name" data-field="name" value="" placeholder="Unique name">
                <button class="btn btn-outline-primary dropdown-toggle add-export-extension" type="button" data-bs-toggle="dropdown" aria-expanded="false">.csv</button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.csv')">.csv</a></li>
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.csv.gz')">.csv.gz</a></li>
                  <li><a class="dropdown-item" onclick="$(event.target).closest('ul').prev().text('.xlsx')">.xlsx</a></li>
                </ul>
            </div>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-3">{% trans "type"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select add-export-type" aria-label="Select export type" onchange="changeExportType(this)">
               <option disabled selected value>{% trans "Select export type" %}</option>
               <option value="sql">SQL query</option>
               <option value="report">Report</option>
               <option value="customreport">Custom report</option>
             </select>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="sql">
          <div class="col">
             <div class="form-floating">
               <textarea class="form-control add-export-sql"></textarea>
               <label>SQL query</label>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="customreport">
          <div class="col-3 text-nowrap">{% trans "custom report"|capfirst%}</div>
          <div class="col-9">
             <select class="form-select add-export-customreport" aria-label="Select custom report">
               <option disabled selected value>{% trans "Select report" %}</option>
               {% for r in customreports %}<option value="{{r.1}}">{{r.0}}</option>{% endfor %}
             </select>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "report"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select add-export-report">
               <option disabled selected value>{% trans "Select report" %}</option>
               {% for r in reports %}<option value="{{r.1}}">{{r.0}}</option>{% endfor %}
             </select>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "bucket size"|capfirst %}</div>
          <div class="col-9">
             <select class="form-select w-auto add-export-bucket">
               <option value="day">day</option>
               <option value="week" selected>week</option>
               <option value="month">month</option>
               <option value="quarter">quarter</option>
               <option value="year">year</option>
             </select>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "horizon"|capfirst %}</div>
          <div class="col-9">
             <input style="width:4.5em" type="number" class="form-control d-inline arrows add-export-horizon" min="0" max="99" value="12">
             <select class="form-select d-inline w-auto add-export-horizonbucket">
               <option value="day">day</option>
               <option value="week" selected>week</option>
               <option value="month">month</option>
               <option value="quarter">quarter</option>
               <option value="year">year</option>
             </select>
          </div>
        </div>
  </div>
  <div class="col-auto mt-3 mb-3">
    <button type="button" class="btn-close float-end" onclick="toggleAddExport(false, this)"></button>
  </div>
</div>

<script>
function deleteExportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  var dialogcontent;
  if (typeof filename === 'undefined') {
    dialogcontent = "{% trans 'You are about to delete all files' %}";
    filename = 'AllFiles';
  } else {
    dialogcontent = interpolate(gettext("You are about to delete file %s"), [filename]);
  }

  $("#popup").html('<div class="modal-dialog">'+
    '<div class="modal-content">'+
      '<div class="modal-header">'+
        '<h5 class="modal-title">{% trans 'Delete file' %}</h5>'+
        '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +
      '</div>'+
      '<div class="modal-body"><p>'+
      dialogcontent +
      '</p></div>'+
      '<div class="modal-footer justify-content-between">'+
        '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary pull-left" data-bs-dismiss="modal" value="{% trans 'Cancel' %}">'+
        '<input type="submit" id="confirmbutton" role="button" class="btn btn-danger float-end" value="{% trans 'Confirm' %}">'+
      '</div>'+
    '</div>'+
  '</div>' );
  showModal('popup');

  $('#confirmbutton').on('click', function() {
    $.ajax({
      url: "{{request.prefix}}/execute/deletefromfolder/" + folder + "/" + filename + "/",
      type: ("delete").toUpperCase(),
      success: function () {
        if (filename === 'AllFiles') {
          $("#popup .modal-body>p").text("{% trans 'All data files were deleted' %}");
        } else {
          $("#popup .modal-body>p").text(interpolate(gettext("File %s was deleted"), [filename]));
        }
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {location.reload();});
      },
      error: function (result, stat, errorThrown) {
        if (result.status == 401) {
          location.reload();
          return;
        }
        var filelist = result.responseText.split(' / ');
        var elem = $("#popup .modal-body>p");
        if (filelist.length === 1) {
          elem.text(interpolate(gettext("File %s was not deleted"), [filename]));
        } else {
          for (var i = 1; i < filelist.length; i++) {
            if (i === 1) {
              elem.text(interpolate(gettext("File %s was not deleted"), [filelist[i]]));
            } else {
              elem.parent().append('<p>'+interpolate(gettext("File %s was not deleted"), [filelist[i]])+'</p>');
            }
          }
        }
        $("#popup .modal-body>p").addClass('alert alert-danger');
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        }
    })
  })
}

function downloadExportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  if (typeof filename === 'undefined')
    window.open("{{request.prefix}}/execute/downloadfromfolder/" + folder + "/", '_blank');
  else
  	window.open("{{request.prefix}}/execute/downloadfromfolder/" + folder + "/" + filename + '/', '_blank');
}

function toggleAddExport(show, el) {
  var name = $(el).closest(".row").attr("data-file");
  var root = $(el).closest(".card-body");
  root.find("[data-file='" + name + "']").toggleClass("d-none");
}

function saveExport(el) {
  var myform = $(el).closest(".row");
  var data = {
      "name": myform.find(".add-export-name").first().val()
         + myform.find(".add-export-extension").first().html(),
      "type": myform.find(".add-export-type").first().val()
      };
  if (myform.attr("data-file") != "adding-a-new-export") {
    data["currentname"] = myform.attr("data-file");
  }
  if (data["type"]  == "sql") {
    data["sql"] = myform.find(".add-export-sql").first().val();
  } else if (data["type"]  == "report") {
    data["report"] = myform.find(".add-export-report").first().val();
    data["bucket"] = myform.find(".add-export-bucket").first().val();
    data["horizon"] = myform.find(".add-export-horizon").first().val();
    data["horizonbucket"] = myform.find(".add-export-horizonbucket").first().val();
  } else if (data["type"] == "customreport") {
    data["report"] = myform.find(".add-export-customreport").first().val();
  }
  $.ajax({
    url: "{{request.prefix}}/execute/exports/",
    data: JSON.stringify(data),
    type: "POST",
    contentType: "application/json",
    success: function () {
      location.reload();
    },
    error: function (jqXHR, stat, errorThrown) {
      $('#popup').html('<div class="modal-dialog">'+
          '<div class="modal-content">'+
            '<div class="modal-header bg-danger">'+
              '<h5 class="modal-title">'+ gettext("Error")+'</h5>'+
              '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +              '</div>'+
            '<div class="modal-body"><p>'+
              jqXHR.responseText+
            '</p></div>'+
          '</div>'+
      '</div>' );
      showModal('popup');
    }
  });
  event.preventDefault();
}

function deleteExport(el) {
  var name = $(el).closest(".row").attr("data-file");
  $.ajax({
      url: "{{request.prefix}}/execute/exports/",
      data: JSON.stringify({"delete": name}),
      type: "POST",
      contentType: "application/json",
      success: function () {
        location.reload();
      },
      error: function (jqXHR, stat, errorThrown) {
        $('#popup').html('<div class="modal-dialog">'+
            '<div class="modal-content">'+
              '<div class="modal-header bg-danger">'+
                '<h5 class="modal-title">'+ gettext("Error")+'</h5>'+
                '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +              '</div>'+
              '<div class="modal-body"><p>'+
                jqXHR.responseText+
              '</p></div>'+
            '</div>'+
        '</div>' );
        showModal('popup');
      }
  });
}

function changeExportType(el) {
  var t = $(el).val();
  var myform = $(el).closest(".col");
  myform.find(".optional[data-type!=" + t + "]").addClass("d-none");
  myform.find(".optional[data-type=" + t + "]").removeClass("d-none");
}

</script>